﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ajeelee.Core.Cache;
using Ajeelee.Core.Utils;
using System.Text.RegularExpressions;
using BoCaiWeb.Model;
using BoCaiWeb.Business;
using System.Collections;

namespace BoCaiWeb.WebSite.Code
{
    public class Utility
    {

        /// <summary>
        /// 获取来源地址
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="toUrl"></param>
        /// <param name="curUrl"></param>
        /// <returns></returns>
        public static string GetUrlReferrer(HttpRequest Request, string toUrl, string curUrl)
        {
            if (Request.UrlReferrer != null && !string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri))
            {
                if (Request.UrlReferrer.AbsoluteUri.ToLower().IndexOf(curUrl.ToLower()) < 0)
                {
                    return Request.UrlReferrer.AbsoluteUri;
                }
            }
            return toUrl;
        }

        #region [ 缓存 ]

        /// <summary>
        /// 获取所有分类
        /// </summary>
        /// <returns></returns>
        public static IList<NewsClass> GetNewsClass()
        {
            string key = "/cache/newsclassall/";
            IList<NewsClass> newsClassList = new List<NewsClass>();
            if (Function.GetCacheObject(key) == null)
            {
                newsClassList = new NewsClassBusinessFactory().CreateNewsClassBusiness().GetAllNewsClass();
                if (newsClassList == null)
                {
                    Function.AddCacheObject(key, newsClassList, DateTime.Now.AddMinutes(20));
                }
            }
            else
            {
                newsClassList = Function.GetCacheObject(key) as IList<NewsClass>;
            }
            return newsClassList;
        }

        /// <summary>
        /// 获取友情链接
        /// </summary>
        /// <returns></returns>
        public static IList<Links> GetLinks()
        {
            string key = "/cache/linksall/";
            IList<Links> linkList = new List<Links>();
            if (Function.GetCacheObject(key) == null)
            {
                linkList = new LinksBusinessFactory().CreateLinksBusiness().GetAllLinks();
                if (linkList == null)
                {
                    Function.AddCacheObject(key, linkList, DateTime.Now.AddDays(1));
                }
            }
            else
            {
                linkList = Function.GetCacheObject(key) as IList<Links>;
            }
            return linkList;
        }
        /// <summary>
        /// 获取顶级栏目
        /// </summary>
        /// <returns></returns>
        public static IList<LanMuInfo> GetParentLanMu(int pid = 0)
        {
            string key = "/cache/parentlanmu/" + pid;
            IList<LanMuInfo> list = new List<LanMuInfo>();
            if (Function.GetCacheObject(key) == null)
            {
                Hashtable ht = new Hashtable();
                ht.Add(LanMuInfoHash.CustomWhere, "LM_PId=" + pid);
                ht.Add(LanMuInfoHash.OrderField, "Sort");
                ht.Add(LanMuInfoHash.OrderDirection, "asc");
                list = new LanMuInfoBusinessFactory().CreateLanMuInfoBusiness().GetAllLanMuInfo(ht);
                if (list == null)
                {
                    Function.AddCacheObject(key, list, DateTime.Now.AddDays(1));
                }
            }
            else
            {
                list = Function.GetCacheObject(key) as IList<LanMuInfo>;
            }
            return list;
        }

        #endregion

        /// <summary>
        /// 去除 HTML tag  google "StripHTML" 得到
        /// </summary>
        /// <param name="HTML">源</param>
        /// <returns>结果</returns>
        public static string StripHTML(string HTML)
        {
            string[] Regexs ={
                                    @"([\r\n])[\s]+",
                                    @"&(quot|#34);",
                                    @"&(amp|#38);",
                                    @"&(lt|#60);",
                                    @"&(gt|#62);",
                                    @"&(nbsp|#160);",
                                    @"&(iexcl|#161);",
                                    @"&(cent|#162);",
                                    @"&(pound|#163);",
                                    @"&(copy|#169);",
                                    @"&#(\d+);",
                                    @"-->",
                                    @"<!--.*\n" ,
                                    @"<script[^>]*?>.*?</script>",
                                    @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>"
                                };

            string[] Replaces ={
                                    "",
                                    "\"",
                                    "&",
                                    "<",
                                    ">",
                                    " ",
                                    "\xa1", //chr(161),
                                    "\xa2", //chr(162),
                                    "\xa3", //chr(163),
                                    "\xa9", //chr(169),
                                    "",
                                    "\r\n",
                                    "",
                                    "",
                                    ""
                                };

            string s = HTML;
            for (int i = 0; i < Regexs.Length; i++)
            {
                s = new Regex(Regexs[i], RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(s, Replaces[i]);
            }
            s.Replace("<", "");
            s.Replace(">", "");
            s.Replace("\r\n", "");
            return s;
        }

        #region [ 生成缩略图 ]

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图片路径（相对路径）</param>
        /// <param name="Stream">缩略图路径（相对路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumMode mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(originalImagePath));
            bool rel = MakeThumbnail(originalImage, thumbnailPath, width, height, mode);
            originalImage.Dispose();
            return rel;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图片路径（相对路径）</param>
        /// <param name="Stream">缩略图路径（相对路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static bool MakeThumbnail(System.Drawing.Image srcImage, string thumbnailPath, int width, int height, ThumMode mode)
        {
            System.Drawing.Image originalImage = srcImage;
            bool bret = false;  //返回值
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case ThumMode.AutoFill://指定高宽缩放（可能变形）                
                    break;
                case ThumMode.OnlyWidth://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumMode.OnlyHeight://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case ThumMode.AutoZoom://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case ThumMode.AutoZoomIn: //自动缩小方式
                    if (ow > towidth) // 120 > 90 
                    {
                        if (((double)ow) / ((double)oh) > ((double)towidth) / ((double)toheight))
                        {
                            toheight = oh * towidth / ow;
                        }
                        else
                        {
                            towidth = ow * toheight / oh;
                        }
                    }
                    else  // 45  < 200
                    {
                        if (oh <= toheight)  // 45  < 150
                        {
                            towidth = ow;
                            toheight = oh;
                        }
                        else   // 750  > 150
                        {
                            towidth = ow * toheight / oh;
                        }
                    }
                    break;
                case ThumMode.AutoZoomOut: //自动放大方式
                    if (ow < towidth)
                    {
                        if (((double)ow) / ((double)oh) > ((double)towidth) / ((double)toheight))
                        {
                            toheight = oh * towidth / ow;
                        }
                        else
                        {
                            towidth = ow * toheight / oh;
                        }
                    }
                    if (oh >= toheight)
                    {
                        towidth = ow;
                        toheight = oh;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以原图片格式保存
                bitmap.Save(HttpContext.Current.Server.MapPath(thumbnailPath), originalImage.RawFormat);//System.Drawing.Imaging.ImageFormat.Jpeg
                bret = true;
            }
            catch (Exception ex)
            {
                Function.WriteErrorLog(ex);
            }
            finally
            {//释放资源
                bitmap.Dispose();
                g.Dispose();
                originalImage.Dispose();
            }

            return bret;
        }

        /// <summary>
        /// 缩略图生成方式
        /// </summary>
        public enum ThumMode
        {
            /// <summary>
            /// 自动缩小方式。该方式将在原图片与缩略图比例不符时，若原图宽和高都小于缩略图宽和高时,将不做处理；否则将根据需要的缩略图自动将原图片按比例缩小。所生成的缩略图的尺寸将会小于等于所设置的宽和高。 
            /// </summary>
            AutoZoomOut,
            /// <summary>
            /// 自动放大方式。该方式将在原图片与缩略图比例不符时，若原图宽和高都大于缩略图宽和高时,将不做处理；否则将根据需要的缩略图自动将原图片按比例放大。所生成的缩略图的尺寸将会大于等于原图的宽和高。 
            /// </summary>
            AutoZoomIn,
            /// <summary>
            /// 自动缩放方式。该方式将在原图片与缩略图比例不符时，根据需要的缩略图自动将原图片按比例缩小或放大。所生成的缩略图的宽度/高度会严格等于所设置的宽度/高度,对应高度/宽度有可能随原图比例而自动调整。 
            /// </summary>
            AutoZoom,
            /// <summary>
            /// 自动裁剪方式。该方式将在原图片与缩略图比例不符时，将根据需要的缩略图自动从原图片的中间按比例裁剪。所生成的缩略图的尺寸将会严格等于所设置的宽和高。 
            /// </summary>
            AutoCut,
            /// <summary>
            /// 自动填充方式。该方式将在原图片与缩略图比例不符时，将根据需要的缩略图自动将原图片按比例缩小，空白处以白色填充。所生成的缩略图的尺寸将会严格等于所设置的宽和高。 
            /// </summary>
            AutoFill,
            /// <summary>
            /// 强行缩放方式。该方式会将图片根据指定的缩略图宽和高生成缩略图。如果原图片比例与缩略图比例不符，将会强行将图片变形缩放生成缩略图。所生成的缩略图的尺寸将会严格等于所设置的宽和高。
            /// </summary>
            ForceZoom,
            /// <summary>
            /// 仅考虑宽方式。该方式将在原图片与缩略图比例不符时，将只符合缩略图所要求的宽度，不进行裁减也不进行变形。所生成的缩略图的宽度会严格等于所设置的宽，高度有可能随原图比例而自动调整。 
            /// </summary>
            OnlyWidth,
            /// <summary>
            /// 仅考虑高方式。该方式将在原图片与缩略图比例不符时，将只符合缩略图所要求的高度，不进行裁减也不进行变形。所生成的缩略图的高度会严格等于所设置的高，宽度有可能随原图比例而自动调整。 
            /// </summary>
            OnlyHeight
        }
        #endregion
    }
}